<template>
  <view class="page">
    <view class="content">
      <view v-if="show" class="content_form" :style="{ height: arrowup ? '40px' : 'auto' }">
        <uv-form labelPosition="left" :model="formData" ref="form">
          <uv-form-item :label="$t('组织')" borderBottom @click="popup1open">
            <view class="view_input">
              <view class="view_input_left">
                <text>{{ poiId }}</text>
              </view>
              <view class="view_input_right">
                <uv-icon name="arrow-right" size="12"></uv-icon>
              </view>
            </view>
          </uv-form-item>
          <uv-form-item :label="$t('内容')" borderBottom>
            <uv-radio-group labelColor="#000000" v-model="formData.scoredata">
              <uv-radio activeColor="#FD754C" :customStyle="{ flex: 1, justifyContent: 'center' }" :label="$t('全部')"
                :name="0"></uv-radio>
              <uv-radio activeColor="#FD754C" :customStyle="{ flex: 1, justifyContent: 'center' }" :label="$t('预警')"
                :name="1"></uv-radio>
              <uv-radio activeColor="#FD754C" :customStyle="{ flex: 1, justifyContent: 'center' }" :label="$t('差评')"
                :name="2"></uv-radio>
            </uv-radio-group>
          </uv-form-item>
          <uv-form-item :label="$t('渠道')" borderBottom @click="selectType">
            <view class="view_input">
              <view class="view_input_left">
                <text>{{ selectedTypesText }}</text>
              </view>
              <view class="view_input_right">
                <uv-icon name="arrow-right" size="12"></uv-icon>
              </view>
            </view>
          </uv-form-item>
          <uv-form-item :label="$t('查看')" borderBottom>
            <uv-checkbox-group labelColor="#000000" v-model="formData.commentuserwatch">
              <uv-checkbox activeColor="#FD754C" :customStyle="{ flex: 1, justifyContent: 'center' }" :name="1">{{
                $t("已读") }}</uv-checkbox>
              <uv-checkbox activeColor="#FD754C" :customStyle="{ flex: 1, justifyContent: 'center' }" :name="0">{{
                $t("未读") }}</uv-checkbox>
            </uv-checkbox-group>
          </uv-form-item>
          <uv-form-item :label="$t('状态')" borderBottom>
            <uv-checkbox-group labelColor="#000000" v-model="formData.state">
              <uv-checkbox activeColor="#FD754C" :customStyle="{ flex: 1, justifyContent: 'center' }" :label="$t('待反馈')"
                name="待反馈"></uv-checkbox>
              <uv-checkbox activeColor="#FD754C" :customStyle="{ flex: 1, justifyContent: 'center' }" :label="$t('已反馈')"
                name="完成"></uv-checkbox>
            </uv-checkbox-group>
          </uv-form-item>
          <uv-form-item :label="$t('日期')" borderBottom>
            <view class="calendarsitem">
              <view class="calendarsitem-icon2" @click="calendars?.open">
                <uv-icon custom-prefix="custom-icon" :name="riqi_o" size="18"></uv-icon>
              </view>

              <view class="calendarsitem-time" @click="calendars?.open">
                <text v-if="formData.feedbackTime.length">{{
                  formData.feedbackTime.join("-")
                  }}</text>
              </view>
              <view class="calendarsitem-icon">
                <uv-icon v-if="formData.feedbackTime.length" @click.stop="formData.feedbackTime = []"
                  name="close-circle"></uv-icon>
              </view>
            </view>
          </uv-form-item>
          <uv-form-item :label="$t('派发')" borderBottom>
            <uv-checkbox-group labelColor="#000000" v-model="formData.issystemfeedback">
              <uv-checkbox activeColor="#FD754C" :customStyle="{ flex: 1, justifyContent: 'center' }" :name="1">{{
                $t("AI派发") }}</uv-checkbox>
              <uv-checkbox activeColor="#FD754C" :customStyle="{ flex: 1, justifyContent: 'center' }" :name="0">{{
                $t("人工派发") }}</uv-checkbox>
            </uv-checkbox-group>
          </uv-form-item>

          <view class="calendarsitem">
            <view class="calendarsitem-button">
              <uv-button shape="circle" :customStyle="defaultButton" @click="
                formData = {
                  dep_id: [],
                  scoredata: 0,
                  type: _type,
                  feedbackTime: [],
                  commentuserwatch: [1, 0],
                };
              refresh();
              ">{{ $t("重置") }}</uv-button>
            </view>
            <view class="calendarsitem-button">
              <uv-button shape="circle" :customStyle="submitButton" @click="refresh">
                {{ $t("筛选") }}</uv-button>
            </view>
          </view>
        </uv-form>
      </view>
      <view>
        <uv-calendars ref="calendars" :data="formData.feedbackTime" allowSameDay mode="range"
          @confirm="confirm"></uv-calendars>
      </view>
      <view v-if="show" class="bg-set" @click="arrowup = !arrowup">
        <text>{{ arrowup ? $t("更多筛选") : $t("收起") }}</text>
        <uv-icon color="#FD754C" :name="arrowup ? 'arrow-down' : 'arrow-up'"></uv-icon>
      </view>
      <view v-if="formData.userId && list.length > 1" class="user-warning-banner">
        <view class="warning-content">
          <text class="warning-text">该用户存在多次评价记录</text>
        </view>
      </view>
      <uv-list :customStyle="{ backgroundColor: 'initial', width: '100%' }">
        <uv-list-item v-for="v in list" :key="v.id" :customStyle="{ marginBottom: '12rpx' }">
          <item :data="v" :clickcontent="clickcontent" :clickuserAvatar="clickuserAvatar" :clickpoiName="clickpoiName"
            info :feedbackset="feedbackset"></item>
        </uv-list-item>
      </uv-list>
    </view>
    <uv-back-top :customStyle="backtopStyle" :iconStyle="backtopiconStyle" :scroll-top="5000"></uv-back-top>
  </view>
  <uv-popup ref="popup1" mode="bottom" @change="(e: any) => pageshow = e.show" :safeAreaInsetBottom="false">
    <view>
      <selectdept ref="Deptref" v-model="formData.dep_id" @close="refresh" multiple>
      </selectdept>
    </view>
  </uv-popup>
</template>

<script setup lang="ts">
import { inject, ref, type Ref } from "vue";
import item from "@/components/comment/item.vue";
import {
  onLoad,
  onPullDownRefresh,
  onReachBottom,
  onShow,
} from "@dcloudio/uni-app";
import type { Ipagedata, Iuser } from "@/interface";
import api from "@/api";
import { computed } from "vue";
import selectdept from "@/components/dept/selectdept.vue";
import {
  submitButton,
  defaultButton,
  backtopStyle,
  backtopiconStyle,
} from "@/util/style";
import { watch } from "vue";
import { assign } from "lodash-es";
import { dicttype, riqi_o } from "@/util/data";
import { useI18n } from "vue-i18n";
const $t = useI18n().t;
const pageshow = ref(false);
const feedbackset = inject("feedbackset", {
  customer: "顾客反馈",
  customershow: 1,
  customerrequired: 1,
  method: "处理方法和结果",
  methodshow: 1,
  methodrequired: 1,
  usershow: 0,
  userrequired: 0,
});
const calendars = ref();
const Deptref = ref();
function clickcontent(e: Eps.BaseUserCommentEntity) {
  uni.navigateTo({
    url: `/pages/comment/commentinfo?feedbackId=${e.feedbackId}&id=${e.id}`,
  });
}

function clickuserAvatar(e: Eps.BaseUserCommentEntity) {
  uni.navigateTo({
    url: `/pages/comment/listindex?userId=${e.userId}&show=1`,
  });
}

function clickpoiName(e: Eps.BaseUserCommentEntity) {
  uni.navigateTo({
    url: `/pages/comment/listindex?poiId=${e.poiId}&show=1`,
  });
}

type IformData = {
  dep_id: string[];
  poiId?: string[];
  scoredata: number;
  type: string[];
  feedbackTime: string[];
  state?: string[];
  resultuser?: string;
  feedbackuser?: string;
  userId?: string;
  commentuserwatch: number[];
  aiidentifylabelid?: string;
  identifylabelid?: string;
  productid?: string;
  issystemfeedback?: number[];
};
const _type: string[] = [
];
const formData = ref<IformData>({
  dep_id: [],
  scoredata: 0,
  type: _type,
  feedbackTime: [],
  commentuserwatch: [1, 0],
  issystemfeedback: [1, 0],
});
const show = ref(false);

const isRefresh = ref(false);
const finished = ref(false);
const list = ref<Eps.BaseUserCommentEntity[]>([]);
let page = ref(0);
let size = ref(20);

const arrowup = ref(true);

function confirm(e: any) {
  formData.value.feedbackTime = [e.range.before, e.range.after];
}

onLoad((option) => {
  if (option?.scoredata) {
    formData.value.scoredata = option?.scoredata;
  }
  if (option?.poiId) {
    formData.value.poiId = [option?.poiId];
  }
  if (option?.type) {
    formData.value.type = [option?.type];
  }
  if (option?.state) {
    formData.value.state = [option?.state];
  }
  if (option?.feedbackuser) {
    formData.value.feedbackuser = option?.feedbackuser;
  }
  if (option?.userId) {
    formData.value.userId = option?.userId;
  }
  if (option?.aiidentifylabelid) {
    formData.value.aiidentifylabelid = option?.aiidentifylabelid.split(",");
  }
  if (option?.identifylabelid) {
    formData.value.identifylabelid = option?.identifylabelid.split(",");
  }
  if (option?.productid) {
    formData.value.productid = option?.productid.split(",");
  }
  if (option?.starttime && option?.endtime) {
    formData.value.feedbackTime = [option?.starttime, option?.endtime];
  }
  if (option?.dep_id) {
    formData.value.dep_id = [option?.dep_id];
  }
  if (!option?.show) {
    show.value = !option?.show;
  }
  // if (option?.feedbacktime1) {
  //     formData.value.nullFields = ['feedbacktime1']
  // }
  refresh();
});
const _dicttype = computed(() => {
  return dicttype;
});

const selectedTypesText = computed(() => {
  if (formData.value.type.length === _dicttype.value.length) {
    return "所有类型";
  }
  if (formData.value.type.length === 0) {
    return "所有类型";
  }
  return formData.value.type
    .map((t) => _dicttype.value.find((d) => d.value === t)?.label)
    .join(",");
});

const poiId = computed(() => {
  if (formData.value.dep_id.length === 1) {
    return Deptref.value?.list.find(
      (c: Eps.DeptEntity) => c.id === formData.value.dep_id[0]
    )?.name;
  } else if (formData.value.dep_id.length === 0) {
    return "所有组织";
  } else {
    return `已筛选：${formData.value.dep_id.length}个组织`;
  }
});

function _load(page: number): Promise<Ipagedata<Eps.BaseUserCommentEntity>> {
  const obj: Record<any, any> = {
    ...formData.value,
  };

  // 如果 scoredata 为 0 (全部)，则不传递此参数
  if (obj.scoredata === 0) {
    delete obj.scoredata;
  } else if (obj.scoredata === 1) {
    // 预警
    obj.issystem = 1;
    delete obj.scoredata; // 删除原始 scoredata
  } else if (obj.scoredata === 2) {
    // 差评
    obj.scoretype = 0;
    delete obj.scoredata; // 删除原始 scoredata
  }

  // 如果 type 包含了所有渠道，则不传递此参数
  if (obj.type && obj.type.length === _type.length) {
    // 假设 _type 包含了所有可能的渠道值
    // 更健壮的检查可能需要比较集合内容，但长度检查通常足够
    delete obj.type;
  }

  // 如果 commentuserwatch 包含已读和未读 (1 和 0)，则不传递此参数
  if (obj.commentuserwatch && obj.commentuserwatch.length === 2) {
    delete obj.commentuserwatch;
  }

  // 如果 state 包含待反馈和已反馈，则不传递此参数
  // 注意：需要根据实际值调整，这里假设 "待反馈" 和 "完成" 是所有状态
  if (obj.state && obj.state.length === 2) {
    delete obj.state;
  } else if (obj.state?.includes("完成")) {
    // 保留只选“已反馈”时的逻辑
    obj.nullFields = ["feedbacktime1"];
    // 如果API不需要 state 参数来过滤已完成，可以取消下一行注释
    // delete obj.state;
  }

  // 如果 issystemfeedback 包含 1 和 0，则不传递此参数
  if (obj.issystemfeedback && obj.issystemfeedback.length === 2) {
    delete obj.issystemfeedback;
  }

  // 如果 dep_id 为空数组 (所有组织)，则不传递此参数
  if (obj.dep_id && obj.dep_id.length === 0) {
    delete obj.dep_id;
  }

  // 如果 feedbackTime 为空数组 (所有日期)，则不传递此参数
  if (obj.feedbackTime && obj.feedbackTime.length === 0) {
    delete obj.feedbackTime;
  }

  // 如果 state 包含 "完成"，添加 nullFields 逻辑 (这段逻辑已在上面合并)
  if (formData.value.state?.includes("完成")) {
    obj.nullFields = ["feedbacktime1"];
  }

  return api("/wechat/comment/page", {
    page,
    size: size.value,
    order: "id",
    sort: "desc",
    ...obj, // 传递过滤后的 obj
  });
}

const popup1 = ref();

function popup1open() {
  popup1.value.open();
}

function selectType() {
  uni.navigateTo({
    url: `/pages/publicsentiment/selecttype?types=${JSON.stringify(
      formData.value.type
    )}`,
    events: {
      acceptDataFromOpenedPage: function (data: any) {
        formData.value.type = data.types;
        refresh();
      },
    },
  });
}

async function refresh() {
  popup1.value?.close();
  page.value = 1;
  const res = await _load(1);
  const commentusercount = await api<any[]>(
    "/wechat/comment/commentusercount",
    { userId: res.list.map((c) => c.userId).filter((n) => Number(n) > 0) }
  );
  list.value = [];
  res.list.forEach((element: any) => {
    list.value.push(
      assign(element, {
        commentusercount:
          commentusercount.find((c) => c.userId === element.userId)?.count ||
          "0",
      })
    );
  });
  isRefresh.value = false;
  if (res.list.length < size.value) {
    finished.value = true;
  } else {
    finished.value = false;
  }
}

onReachBottom(() => {
  console.log("onReachBottom");
  load();
});

onPullDownRefresh(() => {
  refresh().then(() => {
    uni.stopPullDownRefresh();
  });
});

watch(
  () => arrowup.value,
  (e) => {
    if (e) {
      refresh();
    }
  }
);

async function load() {
  if (finished.value === false) {
    page.value = page.value + 1;
    const res = await _load(page.value);
    const commentusercount = await api<any[]>(
      "/wechat/comment/commentusercount",
      { userId: res.list.map((c) => c.userId).filter((n) => Number(n) > 0) }
    );
    if (res.list.length) {
      res.list.forEach((element: any) => {
        list.value.push(
          assign(element, {
            commentusercount:
              commentusercount.find((c) => c.userId === element.userId)
                ?.count || "0",
          })
        );
      });
      if (res.list.length < size.value) {
        finished.value = true;
      }
    } else {
      finished.value = true;
    }
  } else {
    uni.showToast({ title: "没有更多评论了", icon: "none" });
  }
}

defineExpose({
  pageshow,
});
</script>

<style scoped lang="scss">
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100vw;
  background-color: $uni-bg-def1;
}

.content_form {
  width: calc(100vw - 48rpx);
  padding-left: 24rpx;
  padding-right: 24rpx;
  overflow: hidden;
  background-color: $uni-text-color-inverse;
}

.view_input {
  display: flex;
  flex-wrap: wrap;
  flex-shrink: 0;
  flex-grow: 0;
  flex-basis: auto;
  align-items: stretch;
  align-content: flex-start;

  .view_input_left {
    flex: 1;
    overflow: hidden;
    padding-right: 12rpx;
    height: 20px;
    font-size: 15px;
  }

  .view_input_right {
    width: 40rpx;
  }
}

.calendarsitem {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  align-content: center;
  justify-content: space-between;

  .calendarsitem-time {
    flex: 1;
    min-height: 20px;
    text-align: center;
  }

  .calendarsitem-icon {
    width: 80rpx;
    display: flex;
    align-content: center;
    justify-content: center;
  }

  .calendarsitem-icon2 {
    margin-left: 48rpx;
    display: flex;
    align-content: center;
    justify-content: center;
  }

  .calendarsitem-button {
    flex: 1;
    margin-top: 12rpx;
    margin-bottom: 12rpx;
    display: flex;
    justify-content: center;
  }
}

.bg-set {
  height: 70rpx;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  width: 100%;
  text-align: center;
  justify-content: center;
  background-color: #fff;
  gap: 12rpx;

  text {
    color: #fd754c;
    font-size: 24rpx;
  }
}
</style>
